import router from "./index";
import _ from 'lodash';
import { useStore } from "@/store";
import { nProgress } from '@/core/nProgress';
import { ActionTypes } from '@/store/modules/user/action-types';
import { defaultRoutePath, loginRoutePath } from '@/const/path';

router.beforeEach(async (to, from, next) => {
  nProgress.start();
  const store = useStore()
  const meta = to.meta || {};
  const accessToken = store.state.user.userToken?.access_token;
  if (accessToken) {
    if (to.path === loginRoutePath) {
      next(defaultRoutePath);
    } else {
      // 0 进入获取用户基本信息 1 以上就跳过进入正常页面
      // console.log(store.getters);
      if (_.isNil(store.getters.roles) || store.getters.roles.length === 0) {
        try {
          // console.log('获取用户信息');
          // 刷新页面不丢失token重新获取用户信息与菜单
          await store.dispatch(ActionTypes.GET_USER_INFORMATION)
          // await store.dispatch("menuRouterSet");
          // 获取通用数据以及其他操作
          // store.dispatch("getAllCommonData");
          // 请求带有 redirect 重定向时，登录自动重定向到该地址
          const redirect = decodeURIComponent(
            (to.query.redirect as string) || to.path,
          );
          if (to.path === redirect) {
            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            next({ ...to, replace: true });
          } else {
            // 跳转到目的路由
            next({ path: redirect });
          }
        } catch (error) {
          console.error(error);
          // await store.dispatch("userLogout");
          next({ path: loginRoutePath });
        }
      } else {
        next();
      }
    }
  } else {
    if (meta.isAuth === false) {
      next();
    } else {
      const redirect = encodeURIComponent(to.fullPath);
      next({
        path: loginRoutePath,
        query: {
          redirect,
        },
      });
    }
  }
});

router.afterEach(() => {
  nProgress.done();
});
